//通过MySQL进行增删改查的demo
const mysql = require('mysql');
const util = require("util");
const querystring =require("querystring");

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'demo'
});
connection.connect(function(error,args){
    if(error){
        throw error;
    }
    else{
        console.log("连接服务器成功");
    }
});

var user={
    insert:function(post,callback){
        connection.query("INSERT INTO `user` (`id`, `name`, `age`, `heigh`) VALUES (NULL, '"+post.name+"', '"+post.age+"', '"+post.heigh+"')", callback);
    },
    delete:function(post,callback){
        if(!post.id){
            callback(new Error("delete,error:ID不能为空"));
            return;
        }
        var id=post.id;

        connection.query('DELETE FROM `user` WHERE `user`.`id` = '+id, callback);
    },
    update:function(post,callback){
        if(!post.id){
            callback(new Error("update,error:ID不能为空"));
            return;
        }
        var id=post.id;
        delete post.id;

        var arr=[];
        for(var key in post){
            arr.push("`"+key+"` = '"+post[key]+"'");
        }
        var sql = "UPDATE `user` SET "+arr.join(",")+" WHERE `id` = "+id;
        connection.query(sql, callback);
    },
    listAll:function(callback){
        connection.query('SELECT * FROM `user`', callback);
    },
    find:function(id,callback){
        connection.query('SELECT * FROM `user` WHERE `id` = '+id, callback);
    }
}
module.exports=user;